<template>
  <div class="product_detail">
    <div class="pd_main">
      <!-- <div class="pd_bg"></div> -->
      <div class="content">
        <div class="info">
          <div class="label">
            <div class="require">*</div>
            <div>报名课程</div>
          </div>
          <div class="cont">
            <van-field
              readonly
              clickable
              :value="params.courseName"
              placeholder="请选择课程"
              @click="showPopup = true"
            />
            <van-popup v-model="showPopup" round position="bottom">
              <!-- <van-picker
                show-toolbar
                :style="{ height: '60%' }"
                :columns="lists"
                value-key="className"
                @cancel="showPopup = false"
                @confirm="onConfirm"
              /> -->
              <van-tree-select
                :items="lists"
                @click-item="onConfirm"
                :active-id.sync="params.courseId"
                :main-active-index.sync="activeIndex"
              />
            </van-popup>
          </div>
        </div>
        <div class="info">
          <div class="label">
            <div class="require">*</div>
            <div>学员姓名</div>
          </div>
          <div class="cont">
            <van-field v-model="params.name" placeholder="请输入学员姓名" class="ipt"></van-field>
          </div>
        </div>
        <div class="info">
          <div class="label">
            <div class="require">*</div>
            <div>学员年龄</div>
          </div>
          <div class="cont">
            <van-field type="number" v-model="params.age" placeholder="请输入学员年龄" class="ipt"></van-field>
          </div>
        </div>
        <div class="info">
          <div class="label">
            <div class="require">*</div>
            <div>联系电话</div>
          </div>
          <div class="cont">
            <van-field v-model="params.mobile" placeholder="请输入联系电话" class="ipt"></van-field>
          </div>
        </div>
        <div class="info">
          <div class="label">
            <div class="require">*</div>
            <div>验证码</div>
          </div>
          <div class="cont">
            <div class="code" :class="sendSucccess ? 'disable' : ''" @click="sendCode">{{!sendSucccess ? '发送验证码' : `${time}s后重新发送`}}</div>
            <van-field v-model="params.code" placeholder="请输入验证码" class="ipt"></van-field>
          </div>
        </div>
        <div class="info">
          <div class="label">
            <div>销售人员</div>
          </div>
          <div class="cont">
            <van-field v-model="params.sale" placeholder="请输入销售人员" class="ipt"></van-field>
          </div>
        </div>
        <div class="info">
          <div class="label">
            <div>其他备注</div>
          </div>
          <div class="cont">
            <van-field type="textarea" v-model="params.remark" placeholder="备注信息" class="ipt"></van-field>
          </div>
        </div>
        <div class="bottom mainBgColor" @click="submit">立即报名</div>
      </div>
    </div>
  </div>
</template>

<script>
import { Field, Picker, Popup, Toast, TreeSelect} from 'vant';
  export default {
    compopnents: {
        'van-field': Field,
        'van-picker': Picker,
        'van-popup': Popup,
        'van-tree-select': TreeSelect
    },
    data() {
      return {
        activeId: 1,
        activeIndex: 0,
        items: [
          {
            text: '精品课程',
            children: [
              {
                text: '美术',
                id: '1'
              },{
                text: '体育',
                id: '2'
              },
            ]
          }
        ],
        sendSucccess: false, //验证码是否发送成功
        time: 60,
        value: '',
        lists: [],
        showPopup: false,
        flag: true,
        userCode: '',
        params: {
          courseName: '',
          courseId: '1',
          name: '',
          age: '',
          mobile: '',
          code: '',
          sale: '',
          remark: ''
        }
      }
    },
    created() {
      this.getAllCourse();
    },
    beforeRouteEnter(to, from ,next) {
      next(async vm => {
        if (!window.localStorage.getItem('px_user_openid')) {
          try {
            let code = vm.getCode(to.path);
            if (!code) return
            let ret = await vm.$http.getUserIfRegister({code})
            localStorage.setItem('px_user_openid', ret.data.result.openId)
            // 保存完整的登录数据到缓存
            vm.$store.dispatch('saveLoginData', ret.data)
          } catch(err) {
            let code = vm.redirectGetCode(to.path);
            let ret = await vm.$http.getUserIfRegister({code})
            localStorage.setItem('px_user_openid', ret.data.result.openId)
            // 保存完整的登录数据到缓存
            vm.$store.dispatch('saveLoginData', ret.data)
          }
        }
      })
    },
    methods: {
      sendCode() {
        if (this.sendSucccess) return;
        if (this.params.mobile.length <= 0) return this.$toast('请输入正确的电话号码');
        let openId = localStorage.getItem('px_user_openid')
        this.$http.sendReservationCode({mobile: this.params.mobile, openId: openId}).then(res => {
          console.log(res, 'sendReservationCode')
          if (res.data.code === 200) {
            this.sendSucccess = true
            this.countDown();
            Toast(res.data.message)
          }
        }).catch(err => {
          console.log(err, '错误')
          Toast(err.data.message)
        })
      },
      // 定时器
      countDown() {
        this.timer = setInterval(() => {
          this.time = this.time - 1
          if (this.time === 0) {
            clearInterval(this.timer)
            this.time = 60
            this.sendSucccess = false;
          }
        }, 1000)
      },


      getAllCourse() {
        this.$http.getAllCourseOnlineType().then(res => {
          this.lists = res.data.result;
        })
      },
      onConfirm(value) {
        this.params.courseName = value.text;
        this.params.courseId = value.id;
        this.showPopup = false;
      },
      async submit() {
        const {courseId, name, age, mobile, code, sale, remark} = this.params
        if (!courseId.length) return this.$toast('请选择课程');
        if (!name.length) return this.$toast('请输入姓名');
        if (!age.length) return this.$toast('请输入年龄');
        if (!mobile.length) return this.$toast('请输入电话号码');
        if (!code.length) return this.$toast('请输入验证码');
        if (!this.flag) return
        let openId = localStorage.getItem('px_user_openid')
        if (!openId) {
            this.$toast('正在获取openId...')

            let code = this.redirectGetCode(to.path);
            let ret = await this.$http.getUserIfRegister({code})
            localStorage.setItem('px_user_openid', ret.data.result.openId)
            // 保存完整的登录数据到缓存
            this.$store.dispatch('saveLoginData', ret.data)

            this.flag = true;
            return;
        }
        let query = {
          applicant: name,
          applicantMobile: mobile,
          applicantAge: age,
          sale: sale,
          code: code,
          openId: localStorage.getItem('px_user_openid'),
          courseId: courseId,
          remarks: remark
        };
        this.$http.submitOrder(query).then(res => {
          this.flag = true;
          this.$router.push({name: 'orderSuccess'})
          this.reset();
        }).catch(err => {
          this.flag = true
          this.$toast(err.data.message)
        })
      },
      reset() {
        this.params = {
          courseName: '',
          courseId: '',
          name: '',
          age: '',
          mobile: '',
          code: '',
          sale: '',
          remark: ''
        }
      }
    }
  }
</script>

<style lang="scss" scoped>
  .product_detail {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    color: #333;
    .pd_main {
      flex: 1;
      position: relative;
    //   padding-top: 55px;
      box-sizing: border-box;
      background: rgba(241, 241, 249, 0.2);
      overflow: scroll;
    //   .pd_bg {
    //     width: 100%;
    //     height: 80px;
    //     position: absolute;
    //     left: 0px; top: 0px;
    //     // background: rgba(241, 241, 249, 0.5);
    //     border-radius: 0px 0px 20px 20px;
    //   }
      .content {
        width: 100%;
        position: relative;
        padding: 20px 20px 0px;
        box-sizing: border-box;
        border-radius: 4px;
        .info {
          display: flex;
          align-items: center;
          margin-bottom: 10px;
          .label {
            width: 70px;
            display: flex;
            align-items: center;
            justify-content: flex-end;
            .require {
              color: red;
              margin-right: 2px;
            }
          }
          .cont {
            background: #fff;
            margin-left: 5px;
            flex: 1;
            overflow: hidden;
            border: 1px solid rgba(222, 222, 222, .4);
            border-radius: 8px;
            position: relative;
            .van-cell::after {
              border: 0;
            }
            .ipt {
              width: 100%;
              height: 1005;
            }
            .code {
              position: absolute;
              top: 0px; bottom: 0px;
              right: 10px;
              margin: auto;
              z-index: 10;
              display: flex;
              align-items:center;
              justify-content: center;
              color: #FF5505;
            }
            .disable {
              color: #999 !important;
            }
          }
        }
        .bottom {
          width: 100%;
          height: 44px;
          margin-top: 80px;
          border-radius: 4px;
          color: #fff;
          font-size: 16px;
          display: flex;
          align-items: center;
          justify-content: center;
        }
      }
    }
  }
</style>
